/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logic;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Usuario;

/**
 *
 * @author root
 */
@WebServlet(name = "ServletCadastro", urlPatterns = {"/ServletCadastro"})
public class ServletCadastro extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
    {
        String acao = request.getParameter("acao");
        
        if(acao.equals("novoCadastro")) //vem de index.jsp, criar novo usuario
        {
            RequestDispatcher dispatcher = request.getRequestDispatcher("cadastrousuario.jsp?anterior=index.jsp");
            dispatcher.forward(request, response);
        }
        else if(acao.equals("editarCadastro")) //vem de home jsp, para editar dados
        {
            RequestDispatcher dispatcher = request.getRequestDispatcher("cadastrousuario.jsp?anterior=home.jsp");
            dispatcher.forward(request, response);
        }
        else if(acao.equals("novoUsuario")) //dados do form cadastro.jsp
        {
            HttpSession session = request.getSession();
            ArrayList<Usuario> usersList = (ArrayList)session.getAttribute("usersList");
            
            String nome = request.getParameter("nome"); //recupera dados do form
            String cidade = request.getParameter("cidade");
            String estado = request.getParameter("estado");
            String telefone = request.getParameter("telefone");
            String email = request.getParameter("email");
            String senha = request.getParameter("senha");
            
            //busca email se ja esta cadastrado
            Usuario usuario, usuarioF=null;
            for(int i=0; i< usersList.size(); i++)
            {
                usuario = usersList.get(i);
                if(email.equals(usuario.getLogin()))
                {
                    usuarioF = usuario;
                }
            }
            
            if(usuarioF != null) //usuario ja existe
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp?acao=usuarioExistente");
                dispatcher.forward(request, response);      
            }
            else //usuario nao existe
            {
                Usuario user = new Usuario("user", nome.toUpperCase(), cidade.toUpperCase(), estado, telefone, email, senha);
            
                usersList.add(user); //adiciona usuario

                session.setAttribute("usersList", usersList);

                RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                dispatcher.forward(request, response);
            }
                        
        }
        else if(acao.equals("alteraDados")) //dados vem de cadastro.jsp
        {
            HttpSession session = request.getSession();
            ArrayList<Usuario> usersList = (ArrayList)session.getAttribute("usersList");
            Usuario usuario = (Usuario) session.getAttribute("usuario");
            Usuario usuarioAux =null, usuarioF=null;
            
            String nome = request.getParameter("nome"); //recupera dados do form
            String cidade = request.getParameter("cidade");
            String estado = request.getParameter("estado");
            String telefone = request.getParameter("telefone");
            String email = request.getParameter("email");
            String senha = request.getParameter("senha");
            
            //se usuario esta cadastrado
            for(int i=0; i< usersList.size(); i++)
            {
                usuarioF = usersList.get(i);
                if(usuarioF.getLogin().equals(usuario.getLogin()))
                {
                    usuarioAux = usuarioF;
                }
            }
            //dropa usuario antigo
            if(usuarioAux != null)
            {
                usersList.remove(usuarioAux); //remove da lista
                Usuario usuarioNovo = new Usuario("user", nome.toUpperCase(), cidade.toUpperCase(), estado, telefone, email, senha);
                usersList.add(usuarioNovo);
                //dropa da sessao
                session.setAttribute("usersList", usersList);
                session.removeAttribute("usuario");
                RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
                dispatcher.forward(request, response);   
            }
            else
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp?acao=Erro ao editar seus dados");
                dispatcher.forward(request, response);   
            }
            
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
